/* 
    获取多个对象（）
*/
const list = document.querySelector('.list');
const tomato = document.querySelector('.tomato');
const quadrant = document.querySelector('.four-quadrant');

// main 主体的对象 
const mList = document.querySelector('.m-list');
const mquadrant = document.querySelector('.m-quadrant');
const mtomato = document.querySelector('.m-tomato');
const bplMid = document.querySelector('.bpl-mid');

bplMid.addEventListener('click',e=>
    location.reload()
);


//绑定监听
list.addEventListener('click', function () {
    let mDisplay = document.querySelector('.main-display');
    let barColor = document.querySelector('.bar-color-background');
    barColor.classList.remove('bar-color-background');
    list.classList.add('bar-color-background');

    mDisplay.classList.remove('main-display');
    mList.classList.add('main-display');
    console.log(list);
});
tomato.addEventListener('click', function () {
    let mDisplay = document.querySelector('.main-display');
    let barColor = document.querySelector('.bar-color-background');
    barColor.classList.remove('bar-color-background');
    tomato.classList.add('bar-color-background');

    mDisplay.classList.remove('main-display');
    mtomato.classList.add('main-display');
    console.log(tomato);
});
quadrant.addEventListener('click', function () {
    let mDisplay = document.querySelector('.main-display');
    let barColor = document.querySelector('.bar-color-background');
    barColor.classList.remove('bar-color-background');
    quadrant.classList.add('bar-color-background');
    mDisplay.classList.remove('main-display');
    mquadrant.classList.add('main-display');
})

const listEnd = document.querySelector('.mlbe-title');
const mlbeContain = document.querySelector('.mlbe-contain');
listEnd.addEventListener('click', function () {
    listEnd.classList.toggle('flex-grow-11');
    mlbeContain.classList.toggle('mlbe-contain-height');
    console.log(mlbeContain);
});

// 界面切换
const submitButton = document.querySelector('.submit-button');
const mlbList = document.querySelector('.mlb-list');
const infoListExitSpan = document.querySelector('.info-list-exit-span');
const addListPosition = document.querySelector('.add-list-position');

mlbList.addEventListener('click',function(){
    addListPosition.classList.toggle('toggle-list-add');
});



// 清单表单信息
const initData = [
    {
        listName: '所有任务'
    }
];
// localStorage.setItem('data', JSON.stringify(initData));
const arrList = JSON.parse(localStorage.getItem('dataList')) || [];
const infoSubmitList = document.querySelector(" .infoList");
const infoListText = document.querySelector(".infoListText");
infoSubmitList.addEventListener('submit', function (e) {
    if (!infoListText.value) {
        return alert('输入内容不能为空')
    }
    arrList.push({ listName: infoListText.value });
    this.reset();
    console.log(initData);
    localStorage.setItem('dataList', JSON.stringify(arrList));
    e.preventDefault();
    render();
    RenderSelectionList();
});

let render = function () {
    const trArr = arrList.map(function (ele, index) {
        return `
    <li class="contain-list" data-id="${index}">
        <section class="contain-list-left" data-list='${index}'>
            <span class="iconfont icon-zuoyoujiantou"></span>
            <span>${ele.listName}</span>
        </section>
        <div class="contain-list-right" data-id="${index + 100}">...</div>
    </li>
        `
    }
    )
    mlbeContain.innerHTML = trArr.join('');
   
}
render();

mlbeContain.addEventListener('click', function (e) {
    if (e.target.tagName === 'DIV') {
        console.log(e.target.tagName);
        if (confirm('如果删除清单，则相应任务皆会删除？')) {
            arrList.splice((e.target.dataset.id - 100), 1)
            localStorage.setItem('dataList', JSON.stringify(arrList));
            render();
            RenderSelectionList();
        }
    }
});
/* 
    清单添加界面的切换
*/
// 用cosnt表示，选择出的标签
const addPendingTaskModule = document.querySelector('.add-pending-task-module');
const functionTask = document.querySelector('.function-task');
// class为form1，用于提交
const inputAddPendingTask = document.querySelector('.add-pending-task');
const submitPendingTask = document.querySelector('.submit-pending-task');
const textcount = document.querySelector('.textcount');
// 输入框的变化
    // 绑定事件监听，事件类型为input。特性：边输入，边激活
inputAddPendingTask.addEventListener('input', function () {

    // 激活后，字体的变化，输入内容长度的展示
    textcount.style['font-size'] = '24px'
    textcount.innerHTML = `${inputAddPendingTask.value.length}/200字`;

    // 背景宽高、颜色变化
    functionTask.style.height = '50px';
    inputAddPendingTask.style['background-color'] = 'rgb(255,255,255)';
    submitPendingTask.style['background-color'] = 'rgb(255,255,255)';
});

// 失去焦点时，一切原路返回
inputAddPendingTask.addEventListener('blur', function () {
    textcount.style['font-size'] = '16px'
    functionTask.addEventListener('mouseenter', function () {
        functionTask.style.height = '50px';
        inputAddPendingTask.style['background-color'] = 'rgb(255,255,255)';
        submitPendingTask.style['background-color'] = 'rgb(255,255,255)';
    });
    functionTask.style.height = '0px';
    inputAddPendingTask.style['background-color'] = 'rgb(242,242,242)';
    submitPendingTask.style['background-color'] = 'rgb(242,242,242)';
});

console.log(addPendingTaskModule);
/* 
    开始对下选框，渲染
*/
const selectionList = document.querySelector('.selection-list');
let RenderSelectionList = function(){
    const selectListArr = arrList.map(function(ele,index){
        return `
            <option value="${index}">${ele.listName}</option> 
        `;
    });
    selectionList.innerHTML = selectListArr.join('');
}
RenderSelectionList();

// 先建立一个数组、存放对象
testPriInfoTaskArr = [
{
    // 输入框，输入的内容
    task:'去学习鸭',
    // 对应清单编号
    tag: 0,
    // 对应四象限编号(1-4)
    quadrant:1,
    // 完成时间的储存
    time: 5,
    // 表示状态的切换，aaad-表示未完成，aaa-表示以完成
    state: 'aaad'
},
];

// 将对应信息存入本地，最后再删除，保证本地有数据，防止后边提取是报错。

/* 
    任务添加
*/

// 从本地提取信息
const priInfoTaskArr = JSON.parse(localStorage.getItem('infoTaskArr')) || [];

const mainInfoTask = document.querySelector('.main-info-task');
const quadrantList = document.querySelector('.quadrant-list');
const countDown = document.querySelector('.countdown');

// 绑定提交的，监听事件
mainInfoTask.addEventListener('submit',function(e){
    // 阻止冒泡
    e.preventDefault();
    // 检测
    if(!inputAddPendingTask.value){
        return alert('任务输入内容不能为空');
    }
    // 向一个数组中，存入提交后的信息
    priInfoTaskArr.push(
        {
            task:inputAddPendingTask.value,
            tag:selectionList.value,
            quadrant:quadrantList.value,
            time: countDown.value,
            state:'aaad'
        }
    );
    // 将priInfoTaskArr输入存入本地
    localStorage.setItem('infoTaskArr', JSON.stringify(priInfoTaskArr));
    // 重置表单
    mainInfoTask.reset();
    // 重新，渲染页面，这两个函数，后面会提及
    display();            // 未完成任务的渲染
    quadrantDisplay();    // 已完成任务的渲染
});
/*

    主体 - 添加信息界面

*/

// 未完成界面
const uncomReverse = document.querySelector('.uncom-reverse');
let testarr = JSON.parse(localStorage.getItem('infoTaskArr')) || [];
const display = function(){

    // 解压，地址储存
    testarr = JSON.parse(localStorage.getItem('infoTaskArr')) || [];

    // 这里运用map函数，遍历testarr数组，并且返回一个新数组
    let testarrDisplay = testarr.map(function(ele,index){

        // 判断条件，aaa/aaad-是判断完成与否的标志，已完成，则返回为空
       if(ele.state=='aaa'){
        return '';
       }

       // 将对象里面储存的，与四象限对应数字，转化为汉字
       let flagQuadrant = '重要 / 紧急';
       if(ele.quadrant==2){
            flagQuadrant = '重要 /不紧急';
       }else if(ele.quadrant==3){
            flagQuadrant = '不重要/ 紧急';
       }else if(ele.quadrant==4){
            flagQuadrant = '不重要/不紧急';
       }
       // 用模板字符串返回
       return `
            <div class="main-process-task ${ele.state}">
                    <div class="unconfirm">
                        <span class="button" data-class=${index}>&nbsp;&nbsp;&nbsp;&nbsp;</span>
                        &nbsp;&nbsp;
                        <span class="task-contain">
                            ${ele.task}
                        </span>
                    </div>  
                    <div class="attribute">
                        <span class="delete" data-id='${index}'>x</span>
                        <span class="att-tag">
                             ${arrList[ele.tag].listName}
                        </span>
                        &nbsp;&nbsp;
                        <span class="att-quadrant">
                            ${flagQuadrant}
                        </span>
                        &nbsp;&nbsp;
                        <span class="att-time" data-time = '${ele.time}'>
                            <span class="iconfont icon-shizhong"></span>
                            ${ele.time}min
                        </span>
                    </div>
                </div>
        `;
    });

    // 渲染
    // 
    /* 转化为字符串，并将其添加到相应的地方 */
    uncomReverse.innerHTML =testarrDisplay.join('');
};
// 调用函数，并渲染
display();

const comReverse = document.querySelector('.com-reverse');
const completedNum = document.querySelector('.completed-num');
// 完成界面
const comDisplay = function(){
        // 解压，地址储存
        testarr = JSON.parse(localStorage.getItem('infoTaskArr')) || [];
        // 记录变量
        let count = 0;

        // 这里运用map函数，遍历testarr数组，并且返回一个新数组
        let testarrDisplay = testarr.map(function(ele,index){
            // 判断条件，aaa/aaad-是判断完成与否的标志，已完成，则返回为空
            if(ele.state=='aaad'){
                return '';
            }
            // 将对象里面储存的，与四象限对应数字，转化为汉字
            let flagQuadrant = '重要 / 紧急';
            if(ele.quadrant==2){
                    flagQuadrant = '重要 /不紧急';
            }else if(ele.quadrant==3){
                    flagQuadrant = '不重要/ 紧急';
            }else if(ele.quadrant==4){
                    flagQuadrant = '不重要/不紧急';
            }

            // 记载，一共有多少条数据因该被渲染
            count++;
            // 用模板字符串返回
           return `
                <div class="main-process-task ${ele.state}">
                        <div class="unconfirm">
                            <span class="button" data-class=${index} style="background-color:rgb(222,222,222)">&nbsp;&nbsp;&nbsp;&nbsp;</span>
                            &nbsp;&nbsp;
                            <span class="task-contain">
                                ${ele.task}
                            </span>
                        </div>  
                        <div class="attribute">
                            <span class="delete" data-id='${index}'>x</span>
                            <span class="att-tag">
                                 ${arrList[ele.tag].listName}
                            </span>
                            &nbsp;&nbsp;
                            <span class="att-quadrant">
                                ${flagQuadrant}
                            </span>
                            &nbsp;&nbsp;
                            <span class="att-time" data-time = '${ele.time}'>
                                <span class="iconfont icon-shizhong"></span>
                                ${ele.time}min
                            </span>
                        </div>
                    </div>
            `;
        });
        
        // 渲染
        // 
        /* 转化为字符串，并将其添加到相应的地方 */
        comReverse.innerHTML =testarrDisplay.join('');
        // 展示，共渲染多少条数据
        completedNum.innerHTML = count;
};


/* comDisplay(); */
/* 
    委托 - 里程碑
*/
// 选择包含所有按钮的父元素
let container = document.querySelector('.ml-main');

// 为父元素添加事件监听器
container.addEventListener('click', function(event) {
    // 确保点击的元素是按钮
    if (event.target && event.target.classList.contains('button')) {
        let dataClassValue = event.target.dataset.class;

        if (priInfoTaskArr[dataClassValue].state === 'aaad') {
            priInfoTaskArr[dataClassValue].state = 'aaa';
        } else {
            priInfoTaskArr[dataClassValue].state = 'aaad';
        }
        
        localStorage.setItem('infoTaskArr', JSON.stringify(priInfoTaskArr));
        display();
        comDisplayAll();
        console.log('触发了');
    }
});
const completed = document.querySelector('.completed');
completed.addEventListener('click',function(){
    if(completed.dataset.id === 'no'){
        completed.dataset.id = 'yes';

        comDisplay();
    }else{
        completed.dataset.id = 'no';
        comReverse.innerHTML = '';
    }
})
let comDisplayAll = function(){
    if(completed.dataset.id === 'yes'){
        comDisplay();
    }
};
// delete对应的元素有无数个，只能用委托,并且是等所有安排好后，在委托。
document.addEventListener('DOMContentLoaded', function() {
    const mainBody = document.querySelector('.main');
    mainBody.addEventListener('click',function(e){
        if(e.target&&e.target.classList.contains('delete')){
            if(confirm('你确定要删除这条数据吗？')){
                let num = e.target.dataset.id;
                priInfoTaskArr.splice(num,1);
                localStorage.setItem('infoTaskArr', JSON.stringify(priInfoTaskArr));
                display();
                comDisplayAll();
                quadrantDisplay();
            }
        }
    });
});
const containList = document.querySelectorAll('.containList');

// 列表 - 区分task - 委托
mlbeContain.addEventListener('click',function(e){
    if(e.target&&e.target.classList.contains('contain-list-left')){
        let num = e.target.dataset.list;
        displayList(num);
        comDisplayList(num);
    }
});

const displayList = function(flag){
    // 获取知识点
        testarr = JSON.parse(localStorage.getItem('infoTaskArr')) || [];
        let testarrDisplay = testarr.map(function(ele,index){
           if(ele.tag !== flag){
            return '';
           }else if(ele.state=='aaa'){
            return '';
           }
           let flagQuadrant = '重要 / 紧急';
           if(ele.tag==2){
           flagQuadrant = '重要 /不紧急';
               }else if(ele.tag==3){
           flagQuadrant = '不重要/ 紧急';
               }else if(ele.tag==4){
           flagQuadrant = '不重要/不紧急';
               }
           return `
                <div class="main-process-task ${ele.state}">
                        <div class="unconfirm">
                            <span class="button" data-class=${index}>&nbsp;&nbsp;&nbsp;&nbsp;</span>
                            &nbsp;&nbsp;
                            <span class="task-contain">
                                ${ele.task}
                            </span>
                        </div>  
                        <div class="attribute">
                            <span class="delete" data-id='${index}'>x</span>
                            <span class="att-tag">
                                 ${arrList[ele.tag].listName}
                            </span>
                            &nbsp;&nbsp;
                            <span class="att-quadrant">
                                ${flagQuadrant}
                            </span>
                            &nbsp;&nbsp;
                            <span class="att-time" data-time = '${ele.time}'>
                                <span class="iconfont icon-shizhong"></span>
                                ${ele.time}min
                            </span>
                        </div>
                    </div>
            `;
        });
    
        // 渲染
        // 
        /* 转化为字符串，并将其添加到相应的地方 */
        uncomReverse.innerHTML =testarrDisplay.join('');
    };
const comDisplayList = function(flag){
    // 获取知识点
        testarr = JSON.parse(localStorage.getItem('infoTaskArr')) || [];
        let count = 0;
        let testarrDisplay = testarr.map(function(ele,index){
           if(ele.tag !== flag){
            return '';
           }else if(ele.state=='aaad'){
            return '';
           }
           let flagQuadrant = '重要 / 紧急';
           if(ele.tag==2){
           flagQuadrant = '重要 /不紧急';
               }else if(ele.tag==3){
           flagQuadrant = '不重要/ 紧急';
               }else if(ele.tag==4){
           flagQuadrant = '不重要/不紧急';
               }
           count++;
           return `
                <div class="main-process-task ${ele.state}">
                        <div class="unconfirm">
                            <span class="button" data-class=${index} style="background-color:rgb(222,222,222)">&nbsp;&nbsp;&nbsp;&nbsp;</span>
                            &nbsp;&nbsp;
                            <span class="task-contain">
                                ${ele.task}
                            </span>
                        </div>  
                        <div class="attribute">
                            <span class="delete" data-id='${index}'>x</span>
                            <span class="att-tag">
                                 ${arrList[ele.tag].listName}
                            </span>
                            &nbsp;&nbsp;
                            <span class="att-quadrant">
                                ${flagQuadrant}
                            </span>
                            &nbsp;&nbsp;
                            <span class="att-time" data-time = '${ele.time}'>
                                <span class="iconfont icon-shizhong"></span>
                                ${ele.time}min
                            </span>
                        </div>
                    </div>
            `;
        });
        
        // 渲染
        // 
        /* 转化为字符串，并将其添加到相应的地方 */
        comReverse.innerHTML =testarrDisplay.join('');
        completedNum.innerHTML = count;
};

/* 
    四象限 - 添加
*/
// 获取四个模块的对应标签
const imporUrgenBottom = document.querySelector('.impor-urgen-bottom');
const importanceNotUrgencyBody = document.querySelector('.importance-notUrgency-body');
const urgencyUnImportanceBody = document.querySelector('.urgency-unImportance-body');
const unImportanceNotUrgencyBody = document.querySelector('.unImportance-notUrgency-body');
// 对四象限 同时渲染
let quadrantDisplay = function(){
    // 从本地解压
    let  testarr = JSON.parse(localStorage.getItem('infoTaskArr')) || [];
    // 用map数组遍历
    let displayOne = testarr.map(function(ele,index){
        // 为第一象限时，返回压缩后的字符串
        if(ele.quadrant==1){
            return `
             <div class="quadrant-task">
                 ${ele.task}
             </div>
            `;
        }
        // 否则返回空
        return '';
    });
    // 用map数组遍历
    let displayTwo = testarr.map(function(ele,index){
        // 为第二象限时，返回压缩后的字符串
        if(ele.quadrant==2){
            return `
             <div class="quadrant-task">
                 ${ele.task}
             </div>
            `;
        }
        // 否则返回空
        return '';
    });
    // 用map数组遍历
    let displayThree = testarr.map(function(ele,index){
        // 为第三象限时，返回压缩后的字符串
        if(ele.quadrant==3){
            return `
             <div class="quadrant-task">
                 ${ele.task}
             </div>
            `;
        }
        // 否则返回空
        return '';
    });
    // 用map数组遍历
    let displayFour = testarr.map(function(ele,index){
        // 为第四象限时，返回压缩后的字符串
        if(ele.quadrant==4){
            return `
             <div class="quadrant-task">
                 ${ele.task}
             </div>
            `;
        }
        // 否则返回空
        return '';
    });

    // 将四个象限对应的数组，通过join()，转化为四个字符串，并通过innerHTML渲染到相应位置
    imporUrgenBottom.innerHTML =displayOne.join('');
    importanceNotUrgencyBody.innerHTML =displayTwo.join('');
    urgencyUnImportanceBody.innerHTML =displayThree.join('');
    unImportanceNotUrgencyBody.innerHTML =displayFour.join('');
    console.log(displayOne.join(''));
    console.log(1);
}

// 调用，该四象限函数，进行首次渲染
quadrantDisplay();

/* 
    对钟表页面的渲染
*/
// 设置变量，用于后边接受定时器，与延时定时器
let timer;

// 运用父级委托
container.addEventListener('click',function(e){
    if(e.target&&e.target.classList.contains('att-time')){
        let numTime = e.target.dataset.time;
        console.log(`${numTime}`);
        if(confirm(`您确定要开启倒计时服务吗？我将于${numTime}分钟后提醒你`)){
            clearInterval(timer); // 清除定时器
            timepiece(numTime);
        }
    }
});

// 获取标签，用于时间显示
const timePlay = document.querySelector('.timeplay');

const timepiece = function(timeFlag) {

    // 总时间（秒）
    let timeAll = timeFlag * 60;
    // 更新显示时间的函数
    // 运用箭头函数调用，相当于java中的lambda表达式
    const updateDisplay = () => {

        // 将时间转换成秒数
        const min = parseInt(timeAll / 60);
        const second = timeAll % 60;
        timePlay.innerHTML = `${min}:${second < 10 ? '0' + second : second}`;
        timeAll--;

        // 当倒计时归0后
        if (timeAll < 0) {
            alert(`定时为${timeFlag}min的定时，时间到喽`)
            clearInterval(timer); // 清除定时器
        }

    };

    // 启动定时器
    // setInterval 中传递的必须是updateDisplay，而不是updateDisplay()
    // 因为（setInterval需要的是一个函数的引用，以便它在每次间隔到达时调用这个函数）
    timer = setInterval(updateDisplay, 1000);
    // 初始显示一次时间
    updateDisplay();

};

